const db = require('../db/index')
const bcrypt = require('bcryptjs')
const jwt = require("jsonwebtoken")
const config = require("../config.js")

exports.getAnnouncementManagement = (req, res) => {
    let pageNum = req.body.pageNum;
    let pageSize = req.body.pageSize;
    let strTitle = ``;
    if (req.body.message_title) {
        strTitle = ` and message_title like '%${req.body.message_title}%'`;
    }
    let strTevel = ``;
    if (req.body.message_level) {
        strTevel = ` and message_level = '${req.body.message_level}'`;
    }

    const sql = "select * from message where message_category = '公告管理' and message_status = 0 order by message_create_time desc" + strTitle + strTevel + ` limit ${(pageNum - 1) * pageSize} ,${pageSize}`;
    db.query(sql, (err, results) => {
        // 执行 SQL 语句失败
        if (err) return res.cc(err);
        const sql1 = "select count(*) as total from message where message_category = '公告管理' and message_status = 0 order by message_create_time desc" + strTitle + strTevel;
        db.query(sql1, (err, results1) => {
            // 执行 SQL 语句失败
            if (err) return res.cc(err);
            res.send({
                // 状态
                status: 0,
                // 状态描述，判断 err 是 错误对象 还是 字符串
                message: '查询成功',
                data: {
                    list: results,
                    total: results1[0].total
                }
            })
        })
    })
}

exports.addAnnouncementManagement = (req, res) => {
    let message_create_time = new Date().toLocaleString();
    const data = {
        message_title: req.body.message_title,
        message_publish_deparment: req.body.message_publish_deparment,
        message_publish_name: req.body.message_publish_name,
        message_category: req.body.message_category,
        message_receipt_object: req.body.message_receipt_object,
        message_level: req.body.message_level,
        message_content: req.body.message_content,
        message_click_number: 0,
        message_create_time
    }
    const sql = "insert into message set ?";
    db.query(sql, data, (err, results) => {
        console.log(results);
        // 执行 SQL 语句失败
        if (err) return res.cc(err);
        // SQL 语句执行成功，但影响行数不为 1
        if (results.affectedRows !== 1) {
            return res.send({ status: 1, message: '新增公告失败' })
        }
        res.send({
            status: 0,
            message: '新增公告成功！',
            data: {
                id: results.insertId,
                department: req.body.message_receipt_object
            }
        })
    })
}


exports.editAnnouncementManagement = (req, res) => {
    let message_update_time = new Date().toLocaleString();
    let data = {
        message_title: req.body.message_title,
        message_publish_deparment: req.body.message_publish_deparment,
        message_category: req.body.message_category,
        message_receipt_object: req.body.message_receipt_object,
        message_level: req.body.message_level,
        message_content: req.body.message_content,
        message_update_time
    }
    let sql = 'update message set ? where id =?';
    db.query(sql, [data, req.body.id], (err, results) => {
        // 执行 SQL 语句失败
        if (err) return res.cc(err);
        // SQL 语句执行成功，但影响行数不为 1
        if (results.affectedRows !== 1) {
            return res.send({ status: 1, message: '修改公告失败' })
        }
        res.send({
            status: 0,
            message: '修改公告成功！'
        })
    })
}

exports.firstDeleteAnnouncementManagement = (req, res) => {
    let message_status = 1;
    let message_delete_time = new Date().toLocaleString();
    let sql = "update message  set  message_status = ?,message_delete_time = ? where id= ?"
    db.query(sql, [message_status, message_delete_time, req.body.id], (err, results) => {
        // 执行 SQL 语句失败
        if (err) return res.cc(err);
        // SQL 语句执行成功，但影响行数不为 1
        if (results.affectedRows !== 1) {
            return res.send({ status: 1, message: '删除失败' })
        }
        res.send({ status: 0, message: '删除成功！' })
    })


}

exports.getSystemMessages = (req, res) => {
    let pageNum = req.body.pageNum;
    let pageSize = req.body.pageSize;
    const sql = "select * from message where message_category = '系统消息' and message_status = 0" + ` limit ${(pageNum - 1) * pageSize} ,${pageSize}`;
    db.query(sql, (err, results) => {
        // 执行 SQL 语句失败
        if (err) return res.cc(err);
        const sql1 = "select count(*) as total from message where message_category = '系统消息' and message_status = 0";
        db.query(sql1, (err, results1) => {
            // 执行 SQL 语句失败
            if (err) return res.cc(err);
            res.send({
                // 状态
                status: 0,
                // 状态描述，判断 err 是 错误对象 还是 字符串
                message: '查询成功',
                data: {
                    list: results,
                    total: results1[0].total
                }
            })

        })
    })

}

exports.editSystemMessages = (req, res) => {
    let message_update_time = new Date().toLocaleString();
    let data = {
        message_title: req.body.message_title,
        message_content: req.body.message_content,
        message_update_time
    }
    let sql = 'update message set ? where id =?';
    db.query(sql, [data, req.body.id], (err, results) => {
        // 执行 SQL 语句失败
        if (err) return res.cc(err);
        // SQL 语句执行成功，但影响行数不为 1
        if (results.affectedRows !== 1) {
            return res.send({ status: 1, message: '修改系统消息失败' })
        }
        res.send({ status: 0, message: '修改系统消息成功！' })
    })
}



exports.getRecycleBin = (req, res) => {
    let pageNum = req.body.pageNum;
    let pageSize = req.body.pageSize;
    const sql = "select * from message where  message_status = 1" + ` limit ${(pageNum - 1) * pageSize} ,${pageSize}`;
    db.query(sql, (err, results) => {
        // 执行 SQL 语句失败
        if (err) return res.cc(err);
        const sql1 = "select count(*) as total from message where message_status = 1";
        db.query(sql1, (err, results1) => {
            // 执行 SQL 语句失败
            if (err) return res.cc(err);
            res.send({
                // 状态
                status: 0,
                // 状态描述，判断 err 是 错误对象 还是 字符串
                message: '查询成功',
                data: {
                    list: results,
                    total: results1[0].total
                }
            })
        })
    })
}

exports.deleteRecycleBin = (req, res) => {
    let sql = "delete from message where id= ?"
    db.query(sql, req.body.id, (err, results) => {
        // 执行 SQL 语句失败
        if (err) return res.cc(err);
        // SQL 语句执行成功，但影响行数不为 1
        if (results.affectedRows !== 1) {
            return res.send({ status: 1, message: '删除失败' })
        }
        res.send({ status: 0, message: '删除成功！' })
    })
}

exports.reductionRecycleBin = (req, res) => {
    let message_status = 0;
    let sql = "update message set  message_status = ? where id= ?"
    db.query(sql, [message_status, req.body.id], (err, results) => {
        // 执行 SQL 语句失败
        if (err) return res.cc(err);
        // SQL 语句执行成功，但影响行数不为 1
        if (results.affectedRows !== 1) {
            return res.send({ status: 1, message: '还原失败' })
        }
        res.send({ status: 0, message: '还原成功！' })
    })
}




/**
 * 获取未读信息id
 * @route get /msg/getReadList  
 * @summary 获取未读信息id 
 * @group 消息模块
 * @returns {object} 200 - {code:200,msg:'ok',data:null}
 * @returns {Error}  default - {code:500,msg:'error',data:null}
 * @security JWT
 */
// 获取未读信息id
exports.getReadList = (req, res) => {
    let sql = "select read_list from users where id = ?"
    db.query(sql, req.user.id, (err, results) => {
        // 执行 SQL 语句失败
        if (err) return res.cc(err);
        // SQL 语句执行成功，但影响行数不为 1
        if (results.length !== 1) {
            return res.send({ status: 1, message: '获取失败' })
        }
        res.send({
            // 状态
            status: 0,
            // 状态描述，判断 err 是 错误对象 还是 字符串
            message: '获取成功',
            data: JSON.parse(results[0].read_list) || []
        })
    })
}

// 第一次设置未读信息
exports.changeReadList = (req, res) => {
    let sql = "select * from message where message_receipt_object = ? and message_status = 0"
    db.query(sql, req.body.department, (err, results) => {
        // 执行 SQL 语句失败
        if (err) return res.cc(err);
        let ids = results.map(item => item.id);
        let sql1 = "update users set read_list = ?,read_status =1  where id=?";
        db.query(sql1, [JSON.stringify(ids), req.user.id], (err, results) => {
            // 执行 SQL 语句失败
            if (err) return res.cc(err);
            // SQL 语句执行成功，但影响行数不为 1
            if (results.affectedRows !== 1) {
                return res.send({ status: 1, message: '更新失败' })
            }
            res.send({
                // 状态
                status: 0,
                // 状态描述，判断 err 是 错误对象 还是 字符串
                message: '更新成功',
                data: ids
            })
        })
    })
}

// 用户的部门的信息
exports.deparmentMessage = (req, res) => {
    let sql = "select * from message where message_receipt_object = ? and message_status = 0 order by message_create_time desc"
    db.query(sql, req.body.department, (err, results) => {
        // 执行 SQL 语句失败
        if (err) return res.cc(err);
        res.send({
            // 状态
            status: 0,
            // 状态描述，判断 err 是 错误对象 还是 字符串
            message: '查询成功',
            data: results
        })
    })
}

// 信息阅读次数更改
exports.changeReadingTimes = (req, res) => {
    let sql = "update  message set   message_click_number =? where id =?"
    let message_click_number = req.body.message_click_number * 1 + 1;
    db.query(sql, [message_click_number, req.body.id], (err, results) => {
        // 执行 SQL 语句失败
        if (err) return res.cc(err);
        // SQL 语句执行成功，但影响行数不为 1
        if (results.affectedRows !== 1) {
            return res.send({ status: 1, message: '更新失败' })
        }
        res.cc('更新成功', 0)
    })
}

//删减当前用户的未阅读的信息
exports.deleteReadList = (req, res) => {
    let sql = "select read_list from users where id = ?";
    db.query(sql, req.user.id, (err, results) => {
        // 执行 SQL 语句失败
        if (err) return res.cc(err);
        let ids = JSON.parse(results[0].read_list).filter(item => item != req.body.id);
        let sql1 = "update users set read_list = ? where id=?";
        let readList = JSON.stringify(ids);
        db.query(sql1, [readList, req.user.id], (err, results) => {
            // 执行 SQL 语句失败
            if (err) return res.cc(err);
            // SQL 语句执行成功，但影响行数不为 1
            if (results.affectedRows !== 1) {
                return res.send({ status: 1, message: '更新失败' })
            }
            res.send({
                // 状态
                status: 0,
                // 状态描述，判断 err 是 错误对象 还是 字符串
                message: '更新成功',
                data: ids
            })
        })
    })
}


//添加信息id当前用户的未阅读的信息
exports.addReadList = (req, res) => {
    let sql = "select * from users where department = ? and read_status = 1";

    db.query(sql, req.body.department, (err, results) => {
        // 执行 SQL 语句失败
        if (err) return res.cc(err);
        results.forEach(element => {
            let read_list = JSON.parse(element.read_list)

            read_list.push(req.body.id)
            let newRead_list = JSON.stringify(read_list);
            let sql1 = "update users set read_list = ?  where id = ? and read_status = 1";
            db.query(sql1, [newRead_list, element.id], (err, results) => {
                // // 执行 SQL 语句失败
                // if (err) return res.cc(err);
                //             // SQL 语句执行成功，但影响行数不为 1
                //             if (results.affectedRows !== 1) {
                //                 return res.send({ status: 1, message: '更新失败' })
                //             }

            })
        });
        let sql2 = sql = "select * from users where id  = ? and read_status = 1";
        db.query(sql2, req.user.id, (err, results) => {
            // 执行 SQL 语句失败
            if (err) return res.cc(err);
            res.send({
                // 状态
                status: 0,
                // 状态描述，判断 err 是 错误对象 还是 字符串
                message: '更新成功',
                data: results[0].read_list
            })

        })

    })
}

// 更改当前用户的未阅读的信息
exports.editReadList = (req, res) => {
    let sql2 = "select * from users where department = ? and read_status = 1";
    db.query(sql2, req.body.oldDepartment, (err, results) => {
        // 执行 SQL 语句失败
        if (err) return res.cc(err);
        results.forEach(element => {
            let read_list = JSON.parse(element.read_list)
            let ids = read_list.filter(item => item != req.body.id);

            if (read_list.includes(req.body.id)) {
                let sql4 = "update users set read_list = ?  where id = ? and read_status = 1";
                db.query(sql4, [JSON.stringify(ids), element.id], (err, results) => {

                })
            }

        })
    })

    let sql = "select * from users where department = ? and read_status = 1";
    db.query(sql, req.body.department, (err, results) => {
        // 执行 SQL 语句失败
        if (err) return res.cc(err);
        results.forEach(element => {
            let read_list = JSON.parse(element.read_list)

            read_list.push(req.body.id)
            let newRead_list = JSON.stringify(read_list);
            let sql1 = "update users set read_list = ?  where id = ? and read_status = 1";
            db.query(sql1, [newRead_list, element.id], (err, results) => {
                // // 执行 SQL 语句失败
                // if (err) return res.cc(err);
                //             // SQL 语句执行成功，但影响行数不为 1
                //             if (results.affectedRows !== 1) {
                //                 return res.send({ status: 1, message: '更新失败' })
                //             }

            })
        });
        let sql4 = sql = "select * from users where id  = ? and read_status = 1";
        db.query(sql4, req.user.id, (err, results) => {
            // 执行 SQL 语句失败
            if (err) return res.cc(err);
            res.send({
                // 状态
                status: 0,
                // 状态描述，判断 err 是 错误对象 还是 字符串
                message: '更新成功',
                data: results[0].read_list
            })

        })
    })
}
